import "package:ducafe_ui_core/ducafe_ui_core.dart";
import "package:flutter/material.dart";
import "package:flutter_mobx/flutter_mobx.dart";
import "package:go_router/go_router.dart";
import "package:hinge/common/index.dart";
import "package:hinge/common/widgets/custom_dialog.dart";
import "package:hinge/store/root_store.dart";

class PersonalPage extends StatefulWidget {
  final int? userId; // 添加用户ID参数，如果为null则表示查看自己的个人中心

  const PersonalPage({super.key, this.userId});

  @override
  State<PersonalPage> createState() => _PersonalPageState();
}

class _PersonalPageState extends State<PersonalPage>
    with WidgetsBindingObserver {
  final _rootStore = RootStore();
  late UserModel? _pageUser; // 页面显示的用户
  late bool _isCurrentUser; // 是否为当前用户的页面

  @override
  void initState() {
    super.initState();
    _initUserData();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _refreshData();
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    // 记录当前页面路径
    final currentRoute = ModalRoute.of(context);

    // 每次依赖变化时刷新数据（包括路由返回）
    if (currentRoute != null && currentRoute.isCurrent) {
      _refreshData();
    }
  }

  // 刷新页面数据
  void _refreshData() {
    // 重新加载用户数据
    _pageUser =
        widget.userId == null
            ? UserService.getCurrentUser()
            : UserService.getUserById(widget.userId!);

    // 加载用户数据
    _loadUserData();
  }

  // 初始化用户数据
  void _initUserData() {
    final currentUser = UserService.getCurrentUser();

    // 确定页面显示的用户
    if (widget.userId == null) {
      // 没有指定用户ID，显示当前登录用户
      _pageUser = currentUser;
      _isCurrentUser = true;
    } else {
      // 指定了用户ID，查找对应用户
      _pageUser = UserService.getUserById(widget.userId!);
      // 判断是否为当前用户
      _isCurrentUser = currentUser != null && currentUser.id == widget.userId;
    }

    // 加载用户数据
    _loadUserData();
  }

  void _loadUserData() {
    // 如果有页面用户，加载相关数据
    if (_pageUser != null) {
      _rootStore.personalStore.loadUserCollections(_pageUser!.id);
      _rootStore.personalStore.loadUserLikes(_pageUser!.id);
    }
  }

  // 登录提示对话框
  void _showLoginRequiredDialog(String actionName) {
    CustomDialog.show(
      context: context,
      title: 'Login Required',
      content:
          'You need to log in to $actionName. Would you like to log in now?',
      cancelText: 'Cancel',
      confirmText: 'Login',
      onConfirm: () {
        // 导航到登录页面，并添加返回路径参数
        context.push('/login?returnTo=/personal');
      },
    );
  }

  // 处理开始聊天
  Future<void> _handleStartChat() async {
    if (UserService.isGuestUser()) {
      _showLoginRequiredDialog("chat with user");
      return;
    }

    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || _pageUser == null) return;

    try {
      // 查找或创建私聊会话
      final chatSession = await ChatService.findOrCreatePrivateChat(
        currentUser.id,
        _pageUser!.id,
      );

      if (mounted) {
        // 跳转到聊天页面，使用push而不是go
        context.push('/chat/${chatSession.id}');
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('Failed to start chat')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final isGuest = UserService.isGuestUser();

    return WillPopScope(
      onWillPop: () async {
        final router = GoRouter.of(context);
        if (router.canPop()) {
          router.pop();
        } else {
          router.go('/');
        }
        return false;
      },
      child: Scaffold(
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(AssetsImages.personalBg),
              fit: BoxFit.fill,
            ),
          ),
          child: SafeArea(
            child: Column(
              children: [
                _buildHeader(isGuest),
                Observer(builder: (_) => _buildUserInfo(isGuest)),
                SizedBox(height: 44.h),
                _buildCollectionsSection("My Favorites"),
                SizedBox(height: 16.h),
                _buildCollectionsSection("My Likes"),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader(bool isGuest) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 15.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              GestureDetector(
                onTap: () {
                  final router = GoRouter.of(context);
                  if (router.canPop()) {
                    router.pop();
                  } else {
                    router.go('/');
                  }
                },
                child: Icon(IconFont.back, color: Colors.white, size: 28.sp),
              ),
              SizedBox(width: 10.w),
              Text(
                'Personal Center',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w700,
                  color: Colors.white,
                ),
              ),
            ],
          ),
          Row(
            children: [
              if (_isCurrentUser)
                // 自己的个人中心显示消息和设置图标
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        if (isGuest) {
                          _showLoginRequiredDialog("access message center");
                        } else {
                          // 跳转到聊天列表页面
                          context.push('/chats');
                        }
                      },
                      child: Icon(
                        IconFont.chat,
                        color: Colors.white,
                        size: 28.sp,
                      ),
                    ),
                    SizedBox(width: 20.w),
                    GestureDetector(
                      onTap: () {
                        if (isGuest) {
                          _showLoginRequiredDialog("access settings");
                        } else {
                          context.push("/setup").then((_) {
                            // 从设置页面返回时刷新数据
                            _refreshData();
                          });
                        }
                      },
                      child: Icon(
                        IconFont.setup,
                        color: Colors.white,
                        size: 28.sp,
                      ),
                    ),
                  ],
                )
              else
                // 他人的个人中心显示举报图标
                GestureDetector(
                  onTap: () {
                    // 实现举报功能
                  },
                  child: Icon(
                    IconFont.report,
                    color: Colors.white,
                    size: 28.sp,
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildUserInfo(bool isGuest) {
    return Padding(
      padding: EdgeInsets.only(left: 22.w, right: 22.w),
      child: Column(
        children: [
          Row(
            children: [
              Stack(
                children: [
                  CircleAvatar(
                    radius: 31.r,
                    backgroundImage: AssetImage(
                      _pageUser?.avatar ?? AssetsImages.avatar1,
                    ),
                  ),
                  if (isGuest && _isCurrentUser)
                    Positioned(
                      right: 0,
                      bottom: 0,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 5.w,
                          vertical: 2.h,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.orange,
                          borderRadius: BorderRadius.circular(4.r),
                        ),
                        child: Text(
                          'Guest',
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
              SizedBox(width: 15.w),
              Text(
                _pageUser?.nickname ?? "Meadow",
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w700,
                  color: Colors.white,
                ),
              ),
              Spacer(),
              // 只有查看他人个人主页时才显示聊天按钮
              if (!_isCurrentUser)
                GestureDetector(
                  onTap: _handleStartChat,
                  child: Container(
                    width: 106.w,
                    height: 40.h,
                    decoration: ShapeDecoration(
                      color: const Color(0xFFBD88FF),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(28.r),
                      ),
                      shadows: [
                        BoxShadow(
                          color: Color(0x549266C7),
                          blurRadius: 4.r,
                          offset: Offset(0, 4),
                          spreadRadius: 0,
                        ),
                      ],
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      spacing: 4,
                      children: [
                        Text(
                          'Chat',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
            ],
          ),
          SizedBox(height: 15.h),
          Row(
            children: [
              Expanded(
                child: Text(
                  _pageUser?.description ?? "",
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w400,
                    fontFamily: "Inter",
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCollectionsSection(String title) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      decoration: ShapeDecoration(
        gradient: LinearGradient(
          begin: Alignment(0.50, -0.00),
          end: Alignment(0.50, 1.00),
          colors: [const Color(0xFFDFC5FF), const Color(0xFFE7D8FF)],
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.only(left: 12.w, bottom: 10.h, top: 12.h),
            child: Text(
              title,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
                color: Color(0xFF150555),
              ),
            ),
          ),
          SizedBox(
            height: 215.h,
            child: Observer(
              builder: (_) {
                final isGuest = UserService.isGuestUser();
                final perfumes =
                    title == "My Favorites"
                        ? _rootStore.personalStore.userLikes
                        : _rootStore.personalStore.userCollections;

                if (isGuest && _isCurrentUser) {
                  return _buildLoginPrompt();
                }

                if (perfumes.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          AssetsImages.empty,
                          width: 80.w,
                          height: 80.h,
                        ),
                        SizedBox(height: 10.h),
                        Text(
                          title == "My Favorites"
                              ? "No Favorites Yet"
                              : "No Likes Yet",
                          style: TextStyle(
                            color: Color(0xFF150555),
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  );
                }

                return ListView.builder(
                  padding: EdgeInsets.symmetric(horizontal: 15.w),
                  scrollDirection: Axis.horizontal,
                  itemCount: perfumes.length,
                  itemBuilder: (context, index) {
                    final perfume = perfumes[index];
                    return _buildPerfumeCard(perfume);
                  },
                );
              },
            ),
          ),
          SizedBox(height: 12.h),
        ],
      ),
    );
  }

  Widget _buildPerfumeCard(PerfumeModel perfume) {
    return GestureDetector(
      onTap: () {
        context.push("/detail/${perfume.id}");
      },
      child: Container(
        width: 164.w,
        height: 215.h,
        margin: EdgeInsets.only(right: 10.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15.r),
          image: DecorationImage(
            image: AssetImage(perfume.url),
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  // 构建登录提示
  Widget _buildLoginPrompt() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            'Login to view your collections',
            style: TextStyle(color: Colors.white, fontSize: 16.sp),
          ),
          SizedBox(height: 15.h),
          ElevatedButton(
            onPressed: () {
              // 导航到登录页面，并添加返回路径参数
              context.push('/login?returnTo=/personal');
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 10.h),
            ),
            child: Text(
              'Login Now',
              style: TextStyle(
                color: Colors.purple,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
